<?php
namespace Wx\Controller;

use Think\Controller;

class IndexController extends BaseController
{
    public $ip;
    public $cityInfo;
    public $userid;
    public function _initialize()
    {
        parent::_initialize();
        @header('Content-type: text/html;charset=UTF-8');
        $this->ip = '219.137.150.255 ';
        $this->cityInfo = GetIpLookup($this->ip);
        if (session('oto_userId')) {
            $this->userid = session('oto_userId');
        }
    }

    public function index()
    {
        //session('lon',null);
        //存在定位信息
        if (session('lon')) {
            $this->lat = session('lat');
            $this->lon = session('lon');
        }

        $this->orders(); //订单
        //$this->autoConfirm();//自动收货
        $this->my(); //我的
        //$this->r = I('r');
        echo $this->indexPage();
    }

    public function indexPage()
    {
        $db = M('ads');
        $date = date('Y-m-d', time());

        $where['adPositionId'] = '-1';
        $where['_string'] = " '$date' between  adStartDate  and  adEndDate";
        //图片轮播
        $adInfo = $db->where($where)->field('adId,adfile,adurl')->order('adSort ASC')->select();
        $this->assign('adInfo', $adInfo);

        //店铺分类
        $cat = M('goods_cats')->where(array('isShow' => 1, 'catFlag' => 1))->order('catSort ASC')->select();

        $levelOne = [];
        foreach ($cat as $key => $value) {
            if ($value['parentId'] == 0) {
                $levelOne[] = $value;
            }
        }
        $res = $this->arrayPidProcess($cat);
        //print_r($res);exit;
        //统计分类下分类的个数
        foreach ($res as $k => $v) {
            if ($v['child']) {
                $res[$k]['info']['count'] = count($v['child']);
                foreach ($v['child'] as $k1 => $v1) {
                    $res[$k]['child'][$k1]['info']['count'] = count($v1['child']);
                }
            }
        }

        // print_r($res);die;
        $this->assign('levelOne', $levelOne);
        $this->assign('cate', $res);

        return $this->fetch();
    }

    public function my()
    {
        //if(!session('oto_userId')) return $this->fetch;
        $user_id = session('oto_userId');

        $field = [
            'userId',
            'userPhoto',
            'userName',
            'userScore',
            'userMoney',
        ];

        $this->uinfo = M('users')->field($field)->where(['userId' => $user_id])->find();
        $this->assign('userInfo', $this->uinfo);
        //获取优惠券总张数
        $this->coupon = M('youhui_user_link')
            ->where(['user_id' => $user_id, 'u_is_effect' => 1, 'surplus' => array('gt', 0)])
            ->count('surplus');
        //$this->display();
        $this->my_html = $this->fetch('my');
    }

    public function orders()
    {
        //parent::isLogin();
        $page = I('page', 0);
        $limit = 10;
        $start = $page * $limit;

        $field = "o.createTime,o.isSelf,o.isPay,o.needPay,o.orderId,o.areaId1,o.areaId2,o.areaId3,o.communityId,o.deliverMoney,o.orderStatus,o.isRefund,o.isClosed,s.shopName,s.shopId,s.shopImg";
        $orderInfo = M('orders')->field($field)->join('as o left join oto_shops as s on o.shopId=s.shopId')->where(array('o.userId' => session('oto_userId'), 'o.orderFlag' => 1, 'orderType' => array('neq', 4)))->limit($start, $limit)->order('o.orderId DESC')->select();

        $goodsDB = M('order_goods');
        $refundDB = M('refund');

        foreach ($orderInfo as $k => $v) {

            $orderInfo[$k]['goods'] = $goodsDB->where(array('orderId' => $v['orderId']))->select();
            $orderInfo[$k]['count'] = count($orderInfo[$k]['goods']);
            $messageStatus = '';
            if ($orderInfo[$k]['orderStatus'] == 4) {
                $messageStatus = '已完成';
            } else {
                if ($orderInfo[$k]['isRefund'] == 0) {
                    switch ($orderInfo[$k]['orderStatus']) {
                        case -2:$messageStatus = '等待付款';
                            break;
                        case -1:$messageStatus = '订单关闭';
                            break;
                        case 0:$messageStatus = '等待发货';
                            break;
                        case 1:$messageStatus = '商家已受理';
                            break;
                        case 2:$messageStatus = '商家打包中';
                            break;
                        case 3:$messageStatus = '配送中';
                            break;
                        case 4:$messageStatus = '已送达';
                            break;
                    }
                } else {
                    switch ($orderInfo[$k]['isRefund']) {
                        case 1:$messageStatus = '退款中';
                            break;
                        case 2:$messageStatus = '退款成功';
                            break;
                        case 3:$messageStatus = '退款关闭';
                            break;
                    }
                }
            }

            $orderInfo[$k]['messageStatus'] = $messageStatus;
            if ($v['status'] == 4) {
                //检查订单是否评价过
                $isPJ['o.isClosed'] = 0;
                $isPJ['o.orderFlag'] = 1;
                $isPJ['o.orderStatus'] = 4;
                $isPJ['o.orderId'] = $v['orderId'];
                $isPJ['_string'] = "date_sub(curdate(), INTERVAL 7 DAY) <= date(`signTime`)";
                $isPJ = M('orders')->where($isPJ)->join('as o join oto_share as s on o.orderId=s.orderId')->find();
                if ($isPJ) {
                    $orderInfo[$k]['isPJ'] = 1;
                    //追加评价？
                    $addTo = M('share')->where(array('goodsId' => $isPJ['goodsId'], 'orderId' => $isPJ['orderId']))->find();
                    if ($addTo) {
                        $orderInfo[$k]['pj_addTo'] = 1; //已追加
                    } else {
                        $orderInfo[$k]['pj_addTo'] = 0; //没追加
                    }
                } else {
                    if (!$isPJ['isRefund'] || $isPJ['isRefund'] > 0) {
//退款的订单不能评价
                        $orderInfo[$k]['isPJ'] = 1;
                    } else {
                        $orderInfo[$k]['isPJ'] = 0;
                    }
                }
            }
        }
        // print_r($orderInfo);
        $this->info = $orderInfo;

        if (I('ajax') == 1) {
            if ($orderInfo) {
                $res = array('error' => 0, 'message' => $orderInfo);
            } else {
                $res = array('error' => -1, 'message' => 'not more');
            }
            $this->ajaxReturn($res);
        } else {
            $this->orders_html = $this->fetch('Orders/order');
        }

    }

    //自动收货
    private function autoConfirm()
    {

        //最后一次自动收货时间
        $logFile = 'data/last_auto_confirm.log';
        if (is_writable($logFile)) {
            // echo 'The file is writable';
        } else {
            //echo 'The file is not writable';
        }
        $lastTime = intval(@file_get_contents($logFile));

        if (!$lastTime) {@file_put_contents($logFile, time());};

        $nowTime = time();
        //60秒执行一次

        if ($nowTime - $lastTime > 5) {

            $sys = M('sys_configs')->where(array('fieldCode' => 'autoConfirm'))->getField('fieldValue');

            if (!$sys) {return;}
            $second = $sys * 24 * 60 * 60;
            @file_put_contents($logFile, time());
            $sql = "select o.orderStatus,o.shopId,o.orderId,o.needPay,o.orderNo,o.userId from oto_orders as o where o.orderStatus in (3,-5) and o.orderId in(select lo.orderId from oto_log_orders as lo where o.orderId=lo.orderId and lo.logContent='商家已发货' and (UNIX_TIMESTAMP()- UNIX_TIMESTAMP(logTime)>$second) ) ";

            $orderInfo = M()->query($sql);

            $auto = A('Wx/AutoConfirm');
            foreach ($orderInfo as $k => $v) {
                $auto->indexAutoConfirm($v);
            }
        }
    }

    //统计退款，待付款订单数据
    public function stats()
    {
        $info = array();
        //待付款
        $map['isClosed'] = 0;
        $map['orderFlag'] = 1;
        //$map['isPay']=0;
        $map['orderStatus'] = -2;
        $map['orderType'] = array('neq', 4);
        $map['userId'] = session('oto_userId');
        $waitPay = M('orders')->where($map)->count();
        $info['waitPay'] = $waitPay;

        //待发货
        $map['orderStatus'] = array('between', '0,2');
        unset($map['payType']);
        unset($map['isPay']);
        // $map['_string']="isPay=1 or payType=0";
        $deliver = M('orders')->where($map)->count();
        $info['waitDeliver'] = $deliver;

        //待收货
        $map['orderStatus'] = 3;
        $receiving = M('orders')->where($map)->count();
        $info['waitReceiving'] = $receiving;

        //待评价
        //AND ( date_sub(curdate(), INTERVAL 7 DAY) <= date(`signTime`) )
        $sql = 'SELECT o.orderId, o.orderNo, o.areaId1, o.areaId2, o.areaId3, o.shopId, o.deliverMoney, o.payType, o.isSelf, o.deliverType, o.userName, o.userAddress, o.userPhone, o.needPay, s.shopName, s.shopImg FROM `oto_orders` as o left join oto_shops as s on o.shopId=s.shopId WHERE (`isRefund` = 0) AND (`isClosed` = 0) AND (`orderFlag` = 1) AND (`orderStatus` = 4)  AND (`orderType` != 4)  AND orderId NOT IN ( SELECT orderId FROM oto_goods_appraises WHERE orderId = o.orderId AND goodsId  IN ( SELECT goodsId FROM oto_order_goods WHERE orderId = o.orderId ) ) and o.userId=' . session('oto_userId');
        $evaluate = M()->query($sql);
        $total = 0;
        $goodsDB = M('order_goods');
        foreach ($evaluate as $k => $v) {
            $evaluate[$k]['goods'] = $goodsDB->where(array(
                'orderId' => $v['orderId'],
            ))->select();
            $total += count($evaluate[$k]['goods']);
        }
        $this->needEvaluate = $total;
        $info['waitEvaluate'] = $total;

        //售后
        unset($map['_string']);
        $map['orderStatus'] = array('in', "-6,-7,-3");
        $refund = M('orders')->where($map)->count();

        $info['waitRefund'] = $refund;
        return $info;
    }

    //递归分类
    public function arrayPidProcess($data, $res = array(), $pid = '0')
    {
        foreach ($data as $k => $v) {
            if ($v['parentId'] == $pid && $v['isShow'] == 1 && $v['catFlag'] == 1) {
                $res[$v['catId']]['info'] = $v;
                $res[$v['catId']]['child'] = $this->arrayPidProcess($data, array(), $v['catId']);
            }
        }
        return $res;
    }

    //超市
    public function supermarket()
    {
        $parentCatid = (int) I('parentId');
        if (!$parentCatid) {
            return;
        }
        //二级分类
        $sonCat = M('goods_cats')->where(array('parentId' => $parentCatid, 'catFlag' => 1))->field('catId,catName')->order('catSort ASC')->select();
        $this->assign('cat', $sonCat);
        //精品推荐
        $baseMap['goodsCatId1'] = $parentCatid;
        $baseMap['goodsStatus'] = 1;
        $baseMap['isGroup'] = 0;
        $baseMap['isBest'] = 1;
        $baseMap['isSale'] = 1;
        $baseMap['goodsFlag'] = 1;
        $baseMap['goodsStock'] = array('gt', 0);
        $field = "goodsId,goodsName,marketPrice,shopPrice,goodsStock,goodsThums";
        $goods = M('goods')->where($baseMap)->field($field)->limit(3)->select();
        //默认第一个三级显示
        unset($baseMap['isBest']);
        $secondCat = M('goods_cats')->where(array('parentId' => $sonCat[0]['catId'], 'catFlag' => 1))->field('catId,catName')->order('catSort ASC')->select();
        $baseMap['goodsCatId2'] = $sonCat[0]['catId'];
        $goodsHot = M('goods')->where($baseMap)->field($field)->limit(8)->select();

        $this->cateName = M('goods_cats')->where(array('catId' => $parentCatid))->getField('catName');
        $this->assign('secondCat', $secondCat);
        $this->assign('baseGoods', $goods);
        $this->assign('hotGoods', $goodsHot);
        $this->display();
    }

    //加载更多
    public function moreSupermarket()
    {
        $parentCatid = I('parentId', 334);
        //$parentCatid=334;//超市
        $page = I('page');
        //精品推荐
        $catid2 = I('catid2');
        $catid3 = I('catid3');
        if ($catid3) {
            $baseMap['goodsCatId3'] = $catid3;
        } else if ($catid2) {
            $baseMap['goodsCatId2'] = $catid2;
        } else {
            $baseMap['goodsCatId1'] = $parentCatid;
        }
        $baseMap['goodsStatus'] = 1;
        $baseMap['isGroup'] = 0;
        //$baseMap['isBest']=1;
        $baseMap['isSale'] = 1;
        $baseMap['goodsFlag'] = 1;
        $baseMap['goodsStock'] = array('gt', 0);
        $step = 8;
        $limit = $step * $page;
        $field = "goodsId,goodsName,marketPrice,shopPrice,goodsStock,goodsThums";
        $goods = M('goods')->where($baseMap)->field($field)->limit($limit, $step)->select();
        foreach ($goods as $k => $v) {
            $goods[$k]['url'] = U('goodsDetail', array('id' => $v['goodsId']));
        }
        $this->ajaxReturn($goods);
    }

    //加载更多
    public function switchMoreSupermarket()
    {
        // $parentCatid=334;//超市
        $parentCatid = I('parentId', 334);
        $page = I('page');
        //精品推荐
        $baseMap['goodsCatId1'] = $parentCatid;
        $baseMap['goodsStatus'] = 1;
        $baseMap['isGroup'] = 0;
        $baseMap['isBest'] = 1;
        $baseMap['isSale'] = 1;
        $baseMap['goodsFlag'] = 1;
        $baseMap['goodsStock'] = array('gt', 0);
        $step = 3;
        $limit = $step * $page;
        $field = "goodsId,goodsName,marketPrice,shopPrice,goodsStock,goodsThums";
        $goods = M('goods')->where($baseMap)->field($field)->limit($limit, $step)->select();
        foreach ($goods as $k => $v) {
            $goods[$k]['url'] = U('goodsDetail', array('id' => $v['goodsId']));
        }
        $this->ajaxReturn($goods);
    }

    //加载更多评价内容
    public function moereComment()
    {
        //评价晒单
        if (IS_AJAX) {
            $page = I('page');
            $id = I('id');
            $share_db = M('share');
            $shareMap['goodsId'] = $id;
            $shareField = "u.userId,u.userName,s.goodsId,s.shareTitle,s.shareContent,s.shareImg1,s.shareImg2,s.shareImg3,s.shareImg4,s.shareTime,s.star,(4-s.star) as star_";
            $countShare = $share_db->where($shareMap)->count();
            $avgShare = $share_db->where($shareMap)->avg('star');
            $avgShare = ($avgShare / 5) * 100;
            $step = 5;
            $star = $step * $page;
            $shareInfo = $share_db->where($shareMap)->field($shareField)->join('as s left join oto_users as u on u.userId=s.userId')->limit($star, $step)->select();
            $this->ajaxReturn($shareInfo);
        }
    }

    /**
     * 根据商品ID返回店铺ID
     */
    public function getShopIdByGoodsId($goodsId)
    {
        $shopId = M('goods')->where(array('goodsId' => $goodsId))->getField('shopId');
        return $shopId;
    }
    /**
     * 操作成功 status=0
     */
    public function ajaxSuccess()
    {
        $this->ajaxReturn(array('status' => 0));
    }

    /**
     * 操作失败 status=-1
     */
    public function ajaxFail()
    {
        $this->ajaxReturn(array('status' => -1));
    }

    /**
     * 需要登录 status=-2
     */
    public function ajaxNeedLogin()
    {
        $this->ajaxReturn(array('status' => -2));
    }

    /**
     * 关注商品
     */
    public function attenTition()
    {
        if (IS_AJAX) {
            if (!$this->userid) {
                return $this->ajaxNeedLogin();
            }

            $id = I('goodsId');
            $db = M('favorites');
            $map['targetId'] = $id;
            $map['userId'] = $this->userid;
            $map['favoriteType'] = 0;
            $isExis = $db->where($map)->find();
            if ($isExis) {
                $del = $db->where($map)->delete();
                if ($del) {
                    $this->ajaxSuccess();
                } else {
                    $this->ajaxFail();
                }
            } else {
                $map['createTime'] = date('Y-m-d H:i:s', time());
                $add = $db->add($map);
                if ($add) {
                    $this->ajaxSuccess();
                } else {
                    $this->ajaxFail();
                }
            }
        }
    }

}
